/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yy.bugzillahelp.timer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Timer;

/**
 *
 * @author hualun-alan
 */
public class TimerCenter implements ActionListener {

    private Timer timer = new Timer(1000, this);
    private HashMap<String, TimerEvent> events = new HashMap<String, TimerEvent>();

    public TimerCenter() {
        timer.setRepeats(true);
        timer.start();

    }

    public boolean isRunning() {
        return timer.isRunning();
    }

    public void start() {
        timer.start();
    }

    public synchronized void addTimerEvent(String title, TimerEvent event) {
        if (event == null) {
            return;
        }

        if (!events.containsValue(event)) {
            if (title == null || title.isEmpty()) {
                events.put(UUID.randomUUID().toString(), event);
            } else {
                events.put(title, event);
            }
        }
    }

    public synchronized void removeTimerEvent(String title) {
        if (title == null) {
            return;
        }

        events.remove(title);
    }

    public synchronized void removeTimerEvent(TimerEvent event) {
        if (event == null) {
            return;
        }

        String title = "";
        for (Map.Entry<String, TimerEvent> entry : events.entrySet()) {
            if (entry.getValue() == event) {
                title = entry.getKey();
                break;
            }
        }

        if (title != null && !title.isEmpty()) {
            events.remove(title);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        for (TimerEvent timerEvent : events.values()) {
            if (timerEvent.throughCondition()) {
                timerEvent.actionPerformed(e);
            }
        }
    }

    public static void main(String[] args) {
        TimerCenter timerCenter = new TimerCenter();
        timerCenter.addTimerEvent("test1", new TimerEvent() {

            @Override
            public boolean throughCondition() {
                return false;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("test");
            }
        });
        try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            Logger.getLogger(TimerCenter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
